#!/usr/bin/env python3
"""
简单跨平台壁纸设置脚本
直接运行将桌面壁纸换成指定图片
支持Windows和Linux系统
"""

import os
import sys
import platform
from pathlib import Path

def set_wallpaper(image_path):
    """
    设置桌面壁纸
    :param image_path: 图片文件路径
    """
    # 检查图片文件是否存在
    if not os.path.exists(image_path):
        print(f"错误: 图片文件不存在: {image_path}")
        return False
    
    # 检查文件格式
    valid_extensions = {'.jpg', '.jpeg', '.png', '.bmp', '.tiff', '.webp'}
    file_ext = Path(image_path).suffix.lower()
    if file_ext not in valid_extensions:
        print(f"错误: 不支持的图片格式: {file_ext}")
        print(f"支持的格式: {', '.join(valid_extensions)}")
        return False
    
    # 获取绝对路径
    abs_path = os.path.abspath(image_path)
    print(f"正在设置壁纸: {abs_path}")
    
    # 根据操作系统设置壁纸
    system = platform.system().lower()
    
    if system == "windows":
        return set_windows_wallpaper(abs_path)
    elif system == "linux":
        return set_linux_wallpaper(abs_path)
    else:
        print(f"不支持的操作系统: {system}")
        return False

def set_windows_wallpaper(image_path):
    """设置Windows壁纸"""
    try:
        import ctypes
        # SPI_SETDESKWALLPAPER = 20
        ctypes.windll.user32.SystemParametersInfoW(20, 0, image_path, 3)
        print("✅ Windows壁纸设置成功!")
        return True
    except Exception as e:
        print(f"❌ Windows壁纸设置失败: {e}")
        return False

def set_linux_wallpaper(image_path):
    """设置Linux壁纸"""
    try:
        desktop_env = os.environ.get("XDG_CURRENT_DESKTOP", "").lower()
        session_type = os.environ.get("XDG_SESSION_TYPE", "").lower()
        
        print(f"检测到桌面环境: {desktop_env}, 会话类型: {session_type}")
        
        # GNOME桌面环境 (Ubuntu, Fedora Workstation等)
        if "gnome" in desktop_env or "ubuntu" in desktop_env:
            os.system(f"gsettings set org.gnome.desktop.background picture-uri 'file://{image_path}'")
            print("✅ GNOME壁纸设置成功!")
            return True
        
        # KDE Plasma桌面环境
        elif "kde" in desktop_env:
            os.system(f"plasma-apply-wallpaperimage {image_path}")
            print("✅ KDE壁纸设置成功!")
            return True
        
        # XFCE桌面环境
        elif "xfce" in desktop_env:
            os.system(f"xfconf-query -c xfce4-desktop -p /backdrop/screen0/monitor0/image-path -s {image_path}")
            print("✅ XFCE壁纸设置成功!")
            return True
        
        # MATE桌面环境
        elif "mate" in desktop_env:
            os.system(f"gsettings set org.mate.background picture-filename '{image_path}'")
            print("✅ MATE壁纸设置成功!")
            return True
        
        # Wayland会话通用方法
        elif session_type == "wayland":
            os.system(f"swaymsg output '*' bg {image_path} fill")
            print("✅ Wayland壁纸设置成功!")
            return True
        
        # 通用方法 - 使用feh (常用于轻量级桌面如i3wm, openbox等)
        else:
            result = os.system(f"feh --bg-fill {image_path}")
            if result == 0:
                print("✅ 使用feh设置壁纸成功!")
                return True
            else:
                print("❌ 壁纸设置失败，请检查是否安装了feh: sudo apt install feh")
                return False
                
    except Exception as e:
        print(f"❌ Linux壁纸设置失败: {e}")
        return False
 
def main():
    """主函数"""
    print("=== 简单壁纸设置工具 ===")
    print(f"操作系统: {platform.system()}")
        # 直接指定图片路径
    image_path = "/data/home/w-dingyu01@uos/Pictures/Screenshots/截图_选择区域_20251029091213.png"
    success = set_wallpaper(image_path)
    
    
    # # 如果提供了命令行参数，使用参数作为图片路径
    # if len(sys.argv) > 1:
    #     image_path = sys.argv[1]
    # else:
    #     # 如果没有参数，提示用户输入
    #     image_path = input("请输入图片文件路径: ").strip().strip('"').strip("'")
    
    # # 设置壁纸
    # success = set_wallpaper(image_path)
    
    if success:
        print("🎉 壁纸设置完成!")
    else:
        print("💥 壁纸设置失败，请检查以上错误信息")
        sys.exit(1)

if __name__ == "__main__":
    main()